iT邦幫忙

2024 iThome 鐵人賽

DAY 5
0

物件架構、屬性訪問和方法


物件架構
物件字面量是一種用花括號 {} 建立物件的方式,每個物件由鍵和值組成,鍵 key 是屬性名,值 value 是屬性值。

項目 說明
key 屬性的名稱,任何字串都可以作為 key
value value 中可以放入任何型別的值,當然也包括物件

物件架構

建立物件
物件可以直接宣告建立,也可以用 new 建立一個新的物件。

// 直接宣告
const phone = {
  make: 'Apple',
  model: 'i16'
};

// 使用 new 建立
const book = new Object();

物件取值
有了物件可以透過點記法(Dot notation)和括弧記法(Bracket notation)取值。

括弧記法(Bracket notation)使用時機:

  1. 屬性的值帶有小數點、空格或是數字時可以使用,記得要加上引號 (單引號或雙引號皆可)
  2. 物件內的屬性不是變數而是一個字串,所以可以用變數宣告的方式取值
// 點記法(Dot notation)
let obj = {};
obj.key = "value";
console.log(obj, obj.key);  // {key: 'value'} 'value’
// 括弧記法(Bracket notation)
let person = {
    name: 'kuku',
    age: 29,
}
let partC = 'name';
console.log(person[partC]);  // kuku

物件賦值
前面提到物件取值可以使用點記法,所以在賦值的時候,也可以使用這樣的方法。
點記法

// 直接宣告
const phone = {
  make: 'Apple',
  model: 'i16'
};

// 使用 new 建立
const book = new Object();

// 點記法賦值
phone.color = 'black';
book.title = 'JavaScript';
book.auther = 'will';

console.log("object::", phone);
console.log("new-object::", book.title);

印出結果

JSON
JSON 是 JavaScript 物件表示法,一種用於儲存和傳輸資料的格式,主要使用 JSON.stringifyJSON.parse 轉換。
簡單來說,JSON格式就是陣列物件的集合。

// Object To JSON
const student = { name: "kuku", grade: "A" };
const jsonString = JSON.stringify(student);

// JSON To Object
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject);

物件迭代
物件的迭代方法很多,目前用最多的主要有以下 4 種方法:

const dog = {
  breed: "gold",
  age: 6
};

/** Getting both key and value */
for (const [key, value] of Object.entries(dog)) {
  console.log(`${key}: ${value}`);
}

// "breed: gold"
// "age: 6"

/** Getting only keys */
for (const key of Object.keys(dog)) {
  console.log(`${key}`);
}

// "breed"
// "age"

/** Getting only value */
for (const value of Object.values(dog)) {
  console.log(`${value}`);
}

// "gold"
// "6"

/** Assign source to target */
const cat = {
  breed: "mix",
  age: 3,
  food: "fish"
};
console.log(Object.assign(cat, dog));

// [object Object] { "breed": "gold", "age": 6, "food": "fish" }

陣列和他的基本操作(push, pop, shift, unshift, map, filter, reduce...)


陣列
陣列就像一個神奇的列表,可以幫助我們將許多東西有順序的放在一起。
陣列

陣列取值只能透過索引取得陣列項目,如果要呼叫 bird,可以用 console.log(animals[2]);
陣列賦值也可以透過索引給值

const animals = ['dog', 'cat', 'bird'];

animals[0] = 'tiger';
console.log(animals);      // // [object Array] (3) ["tiger","cat","bird"]

🔔 陣列的世界讀取資料是從 0 開始,所以要讀取陣列的第 n 筆資料要寫讀取變數 [ n-1 ]

陣列方法
實務上,有很多陣列方法可以操作讓資料可以整理成套件或是畫面可以渲染的架構,以下是目前實務上最常使用到的。

const numbers = [1, 2, 3, 4, 5];

/** 修改原始陣列的方法 */
// adds element at the end of the array 
numbers.push(''); 
console.log(numbers);      // [1,2,3,4,5,""]

// removes the last element of the array 
numbers.pop();
console.log(numbers);      // [1,2,3,4]

// adds the first element of the array 
numbers.unshift(0);
console.log(numbers);      // [0,1,2,3,4,5]

// removes the first element of the array 
numbers.shift();
console.log(numbers);      // [2,3,4,5]

// add elements to the array 
numbers.splice(1, 0, 'hihi');
console.log(numbers);      // [1,"hihi",2,3,4,5]
const numbers = [1, 2, 3, 4, 5];

/** 取得陣列而不會更動原始陣列 */
// the elements concat the array
console.log(numbers.concat(3));          // [1,2,3,4,5,3]

// converts the array to a string
console.log(numbers.toString());         // "1,2,3,4,5"

// return a portion of the array 
console.log(numbers.slice(1, 3));        // [2,3]

// join the elements of the array with the given separator 
console.log(numbers.join('~hi~'));       // "1~hi~2~hi~3~hi~4~hi~5"

// checks if the array contains an element 
console.log(numbers.includes(3));        // true

// returns the index of the element 
console.log(numbers.indexOf(3));         // 2
const numbers = [1, 2, 3, 4, 5];

/** 陣列迴圈 */
// return the first value in the array that meets the condition
console.log(numbers.find((num) => num % 2 === 0));            // 2

// return the first index in the array that meets the condition
console.log(numbers.findIndex((num) => num % 2 === 0));       // 1

// return a new array processed by calling function
console.log(numbers.map((num) => num * 2));                   // [2,4,6,8,10]

// return a new array of filtered
console.log(numbers.filter((num) => num % 2 === 0));          // [2,4]

// iterate over each element
console.log(numbers.reduce((acc, cur) => acc + cur));         // 15

// returns the Boolean value each element meets the conditions
console.log(numbers.every((num) => num < 6));                 // true

// returns a Boolean value one of the elements meets the conditions
console.log(numbers.some((num) => num > 4));                  // true

// returns a new reversed array
console.log(numbers.reverse());                               // [5,4,3,2,1]

// returns a new reversed array
console.log(numbers.at(-1));                                  // 5

補充:ES6 新增 - 陣列過濾方法 Set


MDN文件:Set

將陣列傳入 Set 的建構函式中,移除重複值後再轉換回數組。

// ES5 的寫法
const arr = [1, 2, 3, 2, 3, 4];
const arrFilter = arr.filter((ele, index, arr) => {
  return arr.indexOf(ele) === index;
});

console.log(arrFilter); // [1,2,3,4]
// ES6 的寫法
const arr = [1, 2, 3, 2, 3, 4];
const arrFilter = [...new Set(arr)];

console.log(arrFilter); // [1,2,3,4]

上一篇
第 4 天:函式 function
下一篇
第 6 天:ES6 新特性 - 解構賦值與範本字面量
系列文
30天 JavaScript 提升計畫:從零到精通結合2024年的創新功能22
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言